/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is the ViewMyCurrency extension.
 *
 * The Initial Developer of the Original Code is
 * Will Moffat.
 * Portions created by the Initial Developer are Copyright (C) 2006
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

//dump("// $Id: WILL_StartUpDialogManager.js,v 1.27 2006/07/02 10:03:23 Will Exp $;\n");

VMC.startupManager = null;

VMC.StartUpDialogLoad = function () {
  if (!window.arguments || !window.arguments.length==4) {
    VMC.log('ERR','this window cannot be opened without a completeList, a defaultSourceList, deletePrefs and a return val');
  }
  VMC.startupManager = new VMC.StartUpDialogManager(window.arguments[0],window.arguments[1],window.arguments[2],window.arguments[3]);
};

// this works without seeing the main ViewMyCurrency object - it just gets/sets the prefs
VMC.StartUpDialogManager = function(completeList,defaultSourceList,warnAboutDeletingPrefs,returnVal) {
  var self=this;
  //if (warnAboutDeletingPrefs) { alert('sorry, we got to delete your old prefs'); }

  this._completeList=completeList;
  this._defaultSourceList=defaultSourceList;
  this._returnVal=returnVal;
  
  this._currentlyShowingCurrencyList = null;
  this._listBox = null; // Pointer to the currencyListBox

  this.updateSelectPage  = updateSelectPage;
  this.updateFinalPage   = updateFinalPage; 
  this.doShowAll         = doShowAll;
  this.doFinish          = doFinish;
  this.doCancel          = doCancel;
  this._init = _init;  

  this._init();

  function _init() {
    if (warnAboutDeletingPrefs) {
      VMC.ge('WILL-warnOldPrefs-box').hidden=false;
      VMC.ge('WILL-firstRun-box').hidden=true;
    }
    VMC.updateAndAddHandlerToLinks();

    if (this._listBox) { return } //only init once!
    this._listBox = VMC.ge('VMC-SelectedListBox');

    this._shortCurrencyList = new VMC.CurrencyList();
    this._currentlyShowingCurrencyList = this._shortCurrencyList;

    try {
      var accept_languages = nsPreferences.getLocalizedUnicharPref('intl.accept_languages');
      accept_languages =+ "," + navigator.language; // BUG: Norwegian browser only had "en-gb,en,nn", it was missing "nb-NO"
      var localeCurrencyList = VMC.currencyDB.createListFromLanguages(accept_languages);
      
      if (VMC.CurrencyList.prototype.isValid(localeCurrencyList)) { // will throw exception if cannot find
	this._shortCurrencyList.addList(localeCurrencyList);
	this._listBox.init(this._currentlyShowingCurrencyList);
      }
    } catch (e) {
      VMC.log('WARN','Could not find valid currencies from '+accept_languages+'\nError = '+e);
      this.doShowAll();
    }
  }

//       var locale=navigator.language; // should be something like 'en-GB'

//       try {
// 	// a failure here should not make wizard die
// 	var localCurrency=this._completeList.findFromLocale(locale);
// 	if (localCurrency) {
// 	  this._listBox.selectCurrency(localCurrency);
// 	}
//       } catch (e) {}



  // this should only be called when we are on this page. Otherwise the next button can be grayed out on the wrong page!
  function updateSelectPage() {
    var isInvalid = this._listBox.checkForInvalidAndWarn(true); //only the highlighted currencies in the list count
    VMC.ge('WILL-firstrun-wizard').canAdvance = ! isInvalid;
  }

  function doShowAll() {
    var newButtonLabel;

    var selectedCurrencyList=this._listBox.getSelectedCurrencies();

    if (this._currentlyShowingCurrencyList == this._completeList) {
      // change to shortlist
      this._currentlyShowingCurrencyList = this._shortCurrencyList;
      newButtonLabel = 'Show all currencies';
    } else {
      // chnage to complete list
      this._currentlyShowingCurrencyList = this._completeList;
      newButtonLabel = 'Show shortlist';
    }

    this._listBox.init(this._currentlyShowingCurrencyList);

    if (!selectedCurrencyList.isEmpty()) {
      this._listBox.selectCurrencies(selectedCurrencyList);
    }
    
    VMC.ge('VMC-showAll-button').label = newButtonLabel;
  }

  function doCancel() {
    //alert('WILL: should I warn and say how to do a config later?');
    return true; //let the cancel complete
  }

  function doFinish() {
    var currencyList=this._listBox.getSelectedCurrencies();
    if (currencyList.isEmpty()) { VMC.alert('no selected currencies'); }

    this._returnVal['newTargetCurrencyList']=currencyList;
    return true; // let the Finish happen
  }

  function updateFinalPage() {

    var sentenceJoin = function(list,getTextFunc) {
      if (!list || !list.length) { VMC.log('ERR','Empty list'); }
      if (list.length==1) { return getTextFunc(list[0]); }
      var text = getTextFunc(list[0]);
      for (var i=1; i<list.length-1; i++) { text += ', '+getTextFunc(list[i]);  }
      if (list.length>1) { text += ' and '; }
      text += getTextFunc(list[list.length-1]);
      return text;
    };


    var sourceListItems = this._defaultSourceList.items;

    var label=VMC.ge('WILL-sourceCurrency-label');
    var text=sentenceJoin(sourceListItems, function(item) { return item.description; } );
    label.firstChild.nodeValue=text; //we want line-wrapping so we don't just set the items value

    var targetText = sentenceJoin(this._listBox.getSelectedCurrencies().items, function(item) { return item.description; } );
    VMC.ge('WILL-targetCurrency-label').value=targetText;

    var webServiceStr=sentenceJoin(VMC.webServiceList, function(item) { return item.getName(); } );
    VMC.ge('WILL-webservices-label').value=webServiceStr;
    
  }
};

